<?php

require_once(WSB_XTENSION_PATH . 'image/models/DbTable/Table.php');

class Image_IndexController extends WSB_Xtension_Content
{
	protected $_noViewRenderer = false;
	private $_width;
	private $_height;

	public function init()
	{
		$config = $this->getConfiguration();
		$this->_width = isset($config->_width) ? $config->_width : 600 ;
		$this->_height = isset($config->_height) ? $config->_height : 600 ;
		parent::init();
	}

	public function indexAction()
	{
		$table = $this->getTable();
		$where = $table->getAdapter()->quoteInto('id=?', $this->_container->item_id);
		$row = $table->fetchRow($where);
		if(($row instanceof WSB_Db_Row) && !empty($row->image)) {
			$this->_view->image = WSB_PATH . trim($row->image);
			$this->_view->caption = trim($row->caption);
			$this->_view->alt = trim($row->alttext);
			$this->_view->width = empty($row->width) ? $this->_width : $row->width;
			$this->_view->height = empty($row->height) ? $this->_height : $row->height;
            $this->_view->link = $this->buildLink($row->link);
            $this->_view->layout = intval($row->layout);
            $this->_view->moduleId = $this->_module->id;
			$this->renderView('index.phtml');
		}
	}

	public function getTable()
	{
		return new Image_Model_DbTable_Table();
	}

	public function renderForBackend()
	{
		return $this->indexAction();
	}

	/**
	 * @param string $link
	 * @return array
	 */
	private function buildLink($link)
	{
		$link = strtolower(trim($link));
		if(empty($link)) {
			return array();
		}

		$parts = explode(' ', $link);
		$href = empty($parts[0]) ? '' : $parts[0];
		$target = empty($parts[1]) ? '' : $parts[1];

		if(is_numeric($href)) {
			// Interner Link auf eine Seite
			$href = $this->_view->urlToPage($href);
		} elseif((substr($href, 0, 3) == 'www') ||(substr($href, 0, 7) == 'http://')) {
			// Absolut gesetzter Link
			$href = 'http://' . str_replace('http://', '', $href);
		}

		return array('href' => $href, 'target' => $target);
	}

}
